package server

import (
	"io/ioutil"
	"net/http"
	"os"
	"stforum/databases"
	"stforum/global"
	"stforum/global/model"
	"time"

	"github.com/dingdinglz/dingtools/dingjson"
	"github.com/gin-gonic/gin"
)

func InstallRoute(ctx *gin.Context) {
	j := ctx.PostForm("json")
	json := dingjson.NewFromString(j)
	var InstallData model.InstallModel
	err := json.ConventToStruct(&InstallData)
	var MysqlData model.InstallMysqlModel
	if InstallData.Database == "mysql" {
		err = json.ConventToStruct(&MysqlData)
	}
	if err != nil {
		global.Logger.Error("解析初始化数据出错！错误原因：", err.Error())
		ctx.JSON(http.StatusOK, gin.H{"msg": "err", "err": "解析初始化数据出错，请查看控制台"})
		return
	}
	global.Logger.Debug(InstallData.Description, InstallData.Database, InstallData.Title, InstallData.Port, InstallData.AdminPort)
	global.Logger.Debug(MysqlData.Mysqlhost, MysqlData.Mysqlpassword, MysqlData.Mysqlport, MysqlData.Mysqlusername, MysqlData.Mysqldbname)
	err = databases.SetBaseSetting(j)
	if err != nil {
		global.Logger.Error("存放初始化数据出错！", err.Error())
		ctx.JSON(http.StatusOK, gin.H{"msg": "err", "err": "写数据库出错，请检查是否缺少相关权限"})
		os.Exit(1)
	}
	err2 := ioutil.WriteFile("st.lock", []byte(time.Now().String()), 0666)
	if err2 != nil {
		global.Logger.Error("写文件出错！", err.Error())
		ctx.JSON(http.StatusOK, gin.H{"msg": "err", "err": "写文件出错，请检查是否缺少相关权限"})
		os.Exit(1)
	}
	ctx.JSON(http.StatusOK, gin.H{"msg": "ok"})
}
